#include "iConfig.hpp"

#if GLF_ENABLE_DEBUGGER

#include <glf/debugger/perfCounters.h>

namespace glf
{
namespace debugger
{
	PerfCounters::PerfCounters() :
		Module("PERFCNT"),
		mEnabled(false),
		mPosition(0)
	{
	
	}

	GLF_DEFINE_SINGLETON_WITH_DEP(PerfCounters, Debugger)

	PerfCounters::~PerfCounters()
	{
        if( glf::debugger::Debugger::GetInstance() )
        {
		    glf::debugger::Debugger::GetInstance()->UnregisterModule( this );
        }
	}

	void PerfCounters::UpdateFrame()
	{
		if(mEnabled && GetDebugger()->IsConnected())
		{
			mPosition++;
			if(mPosition >= Counter::BUFFER_SIZE)
			{
				SendPerformanceCounters();
				mPosition = 0;
			}
		}
	}

	void PerfCounters::Parse(int type, PacketReader& in)
	{
		switch(type)
		{
		case MESSAGE_SET_ENABLED:
			mEnabled = in.ReadIntLE() != 0;
			break;
		}
	}

	void PerfCounters::SendPerformanceCounters()
	{
		ScopeMutex mutex;
		PacketWriter& pw = GetPacketWriter();

		pw.Init(MESSAGE_COUNTERS);
		pw.Write((uint)mCounters.size());
		pw.Write(mPosition);
		
		CounterMap::iterator end = mCounters.end();
		for(CounterMap::iterator it = mCounters.begin(); it != end; ++it)
		{
			pw.Write(it->first.c_str());
			Counter& counter = it->second;

			for(uint i = 0; i < mPosition; i++)
				pw.Write(counter.mValues[i]);
		}

		Send(pw);
	}

} //namespace debugger
} //namespace glf

#endif // GLF_ENABLE_DEBUGGER
